package kubayaxi.video.service.base.util.video;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import kubayaxi.video.service.base.util.common.Asserts;
import org.bytedeco.javacpp.Loader;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class VideoUtil {
    /**
     * 提取主方法
     *
     * @param path MP4视频路径
     * @param tmpDir 存放封面图片和网络视频的临时目录
     * @return 视频信息map
     */
    public static Map<String,String> extract(String path, String tmpDir) throws Exception {
        String mp4Path;
        // 如果是网络视频先下载到临时目录
        if (path.startsWith("http")) {
            mp4Path = tmpDir + "/" + IdUtil.simpleUUID() + ".mp4";
            HttpUtil.downloadFile(path, mp4Path);
        } else {
            mp4Path = path;
        }
        Map<String, String> ans = ffmpegExtractImage(mp4Path, tmpDir + "\\" + IdUtil.simpleUUID() + ".jpg");
        // 删除网络视频
        if (path.startsWith("http")) {
            File file = new File(mp4Path);
            boolean delete = file.delete();
            Asserts.isTrue(delete,"文件删除失败");
        }
        return ans;
    }

    /**
     * 提取视频第一帧图片
     *
     * @param mp4Path 视频地址
     * @param picPath 图片存放地址
     * @return 提取的图片地址
     */
    public static Map<String,String> ffmpegExtractImage(String mp4Path, String picPath) throws Exception {
        String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);

        ProcessBuilder extractBuilder =
                new ProcessBuilder(
                        ffmpeg, "-i", mp4Path, "-f", "image2", "-ss", "1","-frames:v", "1", picPath);
        Map<String,String> map;
        Process start = extractBuilder.start();
        map = videoBaseInfo(start.getErrorStream());
        start.waitFor();
        // 添加图片文件路径
        map.put("coverPath",picPath);
        return map;
    }

    /**
     * 获取视频的基本信息
     *
     * @param inputStream ffmpeg的输入流
     * @return
     */
    public static Map<String,String> videoBaseInfo(InputStream inputStream) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        Map<String,String> map = new HashMap<>();
        String line = "";
        while ((line = br.readLine()) != null) {
            // 解析出视频信息
            if (line.contains("Duration")) {
                String duration = line.substring(line.indexOf("Duration") + 10).split(",")[0];
                map.put("duration",duration);
            }
            if (line.contains("Stream")) {
                String ratio = line.split(",")[3].substring(1);
                map.put("ratio",ratio);
                break;
            }
        }
        return map;
    }

    public static void main(String[] args) throws Exception {
//        System.out.println(extract("C:\\Users\\linyuxian\\Downloads\\436977885-1-208.mp4", "C:\\Users\\linyuxian\\Downloads"));
        System.out.println(extract("https://lmusic-1302280959.cos.ap-chengdu.myqcloud.com/lin/foodRecord/video/1063904913-1-208.mp4","C:\\Users\\linyuxian\\Desktop"));
    }
}
